package com.arcsoft.commonbase.widgets

import android.content.Context
import android.graphics.drawable.AnimatedVectorDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ProgressBar
import com.arcsoft.commonbase.R

class SvgProgressBar: ProgressBar {


    private var vectorDrawable: AnimatedVectorDrawable? = null
    private var hasStart = false

    constructor(context:Context):super(context) {
        init(context)
    }

    constructor(context: Context, attrs:AttributeSet):super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr:Int):super(context, attrs, defStyleAttr) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes:Int):super(context, attrs, defStyleAttr, defStyleRes) {
        init(context)
    }


    private fun init(context: Context) {
        indeterminateDrawable = null
        vectorDrawable = context.resources.getDrawable(
            R.drawable.ic_loading_anim,
            context.theme
        ) as AnimatedVectorDrawable
        background = vectorDrawable
    }

    override fun setIndeterminateDrawable(d: Drawable?) {
        vectorDrawable?.let {
            return
        }
        super.setIndeterminateDrawable(d)
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        vectorDrawable?.let {
            if (View.VISIBLE == visibility && !hasStart) {
                hasStart = true
                it.start()
            } else if (View.INVISIBLE == visibility || View.GONE == visibility) {
                hasStart = false
                it.stop()
            }
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        vectorDrawable?.takeIf { !it.isRunning && !hasStart }?.let {
            hasStart = true
            it.start()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        vectorDrawable?.let {
            hasStart = false
            it.stop()
        }
    }
}